/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.support.creator;

import org.jrose.entity.constant.RoleType;
import org.jrose.entity.data.Role;
import org.jrose.entity.data.RoleCareer;
import org.jrose.entity.data.Team;
import org.jrose.service.loader.support.LoaderProvider;
import org.jrose.service.loader.support.UnitTestSupport;

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

import static org.jrose.entity.constant.RoleType.LEADER;

public class RoleCreator extends AbstractCreator<Role> {
    private final Role role;
    private final SortedSet<Integer> masterCareerIds = new TreeSet<>();

    public RoleCreator(LoaderProvider loaderProvider, Team team) {
        super(loaderProvider);
        role = Role.newInstance(team.getId(), nextRoleName(), LEADER, UnitTestSupport.randomRace(), UnitTestSupport.randomGender());
        role.setCareerId(loaderProvider.getCareerLoader().loadInitialCareer().getId());
    }

    public RoleCreator roleType(RoleType roleType) {
        role.setRoleType(roleType);
        return this;
    }

    public RoleCreator masterCareers(Integer... careerIds) {
        masterCareerIds.addAll(Arrays.asList(careerIds));
        return this;
    }

    @Override
    public Role fin() {
        Role role = loaderProvider.getRolePersistence().persist(this.role);
        if (!masterCareerIds.isEmpty()) {
            for (Integer careerId : masterCareerIds) {
                RoleCareer roleCareer = RoleCareer.newInstance(role.getId(), careerId);
                loaderProvider.getRoleCareerPersistence().persist(roleCareer);
            }
        }
        return role;
    }
}
